from flask import Flask, request, make_response, Response
import os
import math
import hashlib
import json

app = Flask(__name__)

package_size = 1024


@app.route("/api/download/<path:filepath>", methods=['GET', ])
def download_main(filepath):
    print("Request match")
    if request.headers.environ['HTTP_PATH_TYPE']=='debug_path':
        filepath = os.path.join('.',filepath)
    if not os.path.isfile(filepath):
        res = make_response('Not Found', 404)
    else:
        md5 = hashlib.md5()
        with open(filepath, 'r') as f:
            data = f.read()
            backage_num = math.ceil(len(data) / package_size)
            md5.update()
            md5_value = md5.hexdigest()
            res = Response(
                data,
                200,
            )
            headers = {
                'md5': md5_value,
                'path': filepath,
                'filename': os.path.split(filepath)[1]
            }
            for iname in headers:
                res.headers.add(iname, headers[iname])
    return res


@app.route("/api/download",methods=['GET'])
def download():
    print('download executed')
    filepath = request.environ['HTTP_FILE_PATH']
    with open(filepath,'rb') as file:
        data = file.read()
        print(data)
    res = Response(
        data,
        200,
    )
    res.headers.add('test','1234')
    return res

@app.route("/api/file_status",methods=['GET'])
def files_status():
    file_path = request.environ['HTTP_FILE_PATH']
    info = {}
    info['name'] = os.path.split(file_path)[1]
    info['size'] = os.path.getsize(file_path)
    info['type'] = 'file' if os.path.isdir(file_path) else 'dir'
    info['mtime'] = os.path.getmtime(file_path)
    encoded_info = json.dumps(info).encode()
    res = Response(
        encoded_info,
        200,
    )
    return res

@app.route("/api/folder_report",methods=['GET'])
def folder_report():
    pass
    folder_path = request.environ['HTTP_FOLDER_PATH']
    folder_info = []
    for filename in os.listdir(folder_path):
        info = {}
        fname = os.path.join(folder_path,filename)
        info['name'] = filename
        info['size'] = os.path.getsize(fname)
        info['type'] = 'file' if os.path.isfile(fname) else 'dir'
        info['mtime'] = os.path.getmtime(fname)
        folder_info.append(info)
    encoded_info = json.dumps(folder_info).encode()
    res = Response(
        encoded_info,
        200
    )
    return res

@app.route("/api/upload_file",methods=['POST'])
def upload_file():
    file_path = request.environ["HTTP_FILE_PATH"]
    data = request.data
    filename = os.path.split(file_path)[1]
    with open(file_path,'wb') as f:
        f.write(data)
    return 'OK'




app.run(host='0.0.0.0', port=8000)
